<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addGood">添加商品</el-button>
        </el-col>
      </el-row>
      <el-table :data="goodsList" style="width: 100%; margin-top: 20px" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="goods_name" label="商品名称" minWidth="300"> </el-table-column>
        <el-table-column prop="goods_price" label="商品价格（元）" minWidth="80px"> </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量"> </el-table-column>
        <el-table-column prop="add_time" label="创建时间">
          <template slot-scope="scope">
            {{scope.row.add_time | DateFormat}}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="small" @click="open_editForm(scope.row.goods_id)">编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="small" @click="confirm_del(scope.row.goods_id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :page-sizes="[1,  5, 10,20]" :page-size="5" layout="total,sizes, prev, pager, next" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <!-- 编辑商品 -->
    <el-dialog title="编辑商品" :visible.sync="editGoodsDialog" width="50%"
      >
      <!-- 内容主体区域 -->
      <el-form label-width="80px" ref="editFormref" :model="editform" @close="resetAddForm('editFormRef')">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editform.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="editform.goods_price"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="goods_number">
          <el-input-number v-model="editform.goods_number" :min="1" label="商品数量"></el-input-number>
        </el-form-item>
        <el-form-item label="重量" prop="goods_weight">
          <el-input autocomplete="off" v-model="editform.goods_weight" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="pics">
          <viewer :images="editform.pics_url">
            <img v-for="(src,index) in editform.pics_url" :src="src" :key="index" class="img">
          </viewer>
          <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" list-type="picture-card"
          :headers="headersObj"  :on-preview="handlePreview" >
          <i class="el-icon-plus"></i>
        </el-upload>

        </el-form-item>
        <!-- <el-form-item label="参数" prop="attrs">
          <el-input autocomplete="off" v-model="editform.attrs"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editGoodsDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm(editform.goods_id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      goodsList: [],
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      // 控制添加商品弹框的显示与隐藏
      editGoodsDialog: false,
      // 上传头部请求
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 修改商品表单
      editform: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 存放图片
        pics: [],
        pics_url: [],
        // 商品的详情描述
        goods_introduce: '',
        attrs: []
      }
    }
  },
  created () {
    this.getGoodsList()
  },
  computed: {},
  watch: {
    'queryInfo.query' (newVal, oldVal) {
      this.getGoodsList()
      console.log(newVal)
    }
  },
  methods: {
    async getGoodsList () {
      const {
        data: res
      } = await this.$http.get('goods', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败！')
      }
      console.log(res.data)
      this.goodsList = res.data.goods
      this.total = res.data.total
    },
    async open_editForm (id) {
      const {
        data: res
      } = await this.$http.get(`goods/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询失败！')
      }
      this.editform = res.data
      const temp = []
      this.editform.pics.forEach(item => {
        temp.push(item.pics_mid_url)
      })
      this.editform.pics_url = temp
      this.editGoodsDialog = true
    },
    // 删除参数
    async confirm_del (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const {
        data: res
      } = await this.$http.delete(`goods/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除信息失败')
      }
      this.getGoodsList()
      return this.$message.success('删除成功！')
    },
    // 重置表单
    resetAddForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 监听 页码值改变事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    // 提交添加商品表单
    submitAddForm (formName) {
      this.addGoodsDialog = false
    },
    // 点击按钮跳转至添加商品
    addGood () {
      this.$router.push('/addGoods')
    },
    handleSuccess (response) {
      this.editform.pics_url.push(response.data.url)
    },
    async submitEditForm (id) {
      const { data: res } = await this.$http.put(`goods/${id}`, this.editform)
      console.log(res.meta)
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }

      this.$message.success('修改成功！')
      this.editGoodsDialog = false
      this.getGoodsList()
    },
    handlePreview () {

    }
  }
}

</script>
<style lang="less" scoped>
  .img {
    width: 146px;
    height: 146px;
  }

</style>
